package jh.com.jhappbf.notify;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Build;
import android.os.IBinder;
import android.text.TextUtils;

import com.android.volley.Request.Priority;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import androidx.core.app.NotificationCompat;
import jh.com.jhappbf.R;
import jh.com.jhappbf.contract.CollectWeigh;
import jh.com.jhappbf.httputils.VolleyCallWebService;
import jh.com.jhappbf.httputils.VolleySingleton;
import jh.com.jhappbf.ui.ContentInfo;
import jh.com.jhappbf.ui.Login;
import jh.com.jhappbf.ui.State;
import jh.com.jhappbf.utils.JsonHelper;
import jh.com.jhappbf.weight.query.QueryWeightDetail;

public class NotifyService extends Service {

    public Notification mNotification = null;
    private NotificationManager nmManager = null;

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        nmManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            String channelId = "default";
            String channelName = "默认通知";
            nmManager.createNotificationChannel(new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH));
        }
        Timer mTimer = new Timer();
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
//				String identifyString  = getIdentifyId();
//				if(identifyString.length() > 0)
//				{
//					doWork(identifyString);
//				}

                if (isWeighSendMessage()) {
                    getWeight();
                }
            }
        }, 0, 5000);
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //	flags = START_STICKY;
        //	flags= Service.START_STICKY;
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Intent i = new Intent(this, NotifyService.class);
        this.startService(i);
    }

    /***
     * 获取身份证号
     */
    private String getIdentifyId() {
        SharedPreferences sharedPreferences = getSharedPreferences("caption", MODE_PRIVATE);
        return sharedPreferences.getString("identify", "");
    }

    /***
     * 获取称重编号
     */
    private Boolean isWeighSendMessage() {
        SharedPreferences sharedPreferences = getSharedPreferences("caption", MODE_PRIVATE);
        return sharedPreferences.getBoolean("sendMessage", false);
    }


    /**
     * 获取数据
     */
    private void doWork(String identify) {
//		getQueue(identify);
//		getAssay(identify);

    }

    /**
     * 获取排队通知
     *
     */
    private void getQueue(String identify) {
        try {
            ArrayList<String> param = new ArrayList<>();
            ArrayList<String> value = new ArrayList<>();
            param.add("identify");
            value.add(identify);
            String methodName = "getQueue";

            Listener<String> listener = response -> {

                JSONObject object = JsonHelper.getJsonObject(response);
                try {
                    if (object != null) {
                        SharedPreferences preferences = getSharedPreferences("caption", MODE_PRIVATE);

                        String id = object.optString("id");
                        String queue = object.optString("queue");
                        String position = object.optString("position");
                        if ("1".equals(position) || "2".equals(position) || "3".equals(position)) {
                            String oldId = preferences.getString("queueId", "");
                            if (!id.equals(oldId)) {
                                Editor editor = preferences.edit();
                                editor.putString("queueId", id);
                                editor.apply();

                                Intent intent = new Intent(NotifyService.this, ContentInfo.class);
                                PendingIntent pi = PendingIntent.getActivity(NotifyService.this, 0,
                                        intent, PendingIntent.FLAG_UPDATE_CURRENT);
                                mNotification = new NotificationCompat.Builder(NotifyService.this, "default")
                                        .setAutoCancel(true)
                                        .setTicker("排队有新信息!")
                                        .setSmallIcon(R.mipmap.ic_launcher)
                                        .setContentTitle("排队通知")
                                        .setContentText(queue)
                                        .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_LIGHTS)
                                        .setWhen(System.currentTimeMillis())
                                        // 设改通知将要启动程序的Intent
                                        .setContentIntent(pi).build();
                                mNotification.flags = Notification.FLAG_AUTO_CANCEL;
                                // 发送通知
                                nmManager.notify(0, mNotification);
                            }
                        } else {
                            Editor editor = preferences.edit();
                            editor.putString("queueId", "");
                            editor.apply();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            };

            ErrorListener errorListener = error -> {
            };

            VolleyCallWebService httpService = new VolleyCallWebService(methodName, param, value, listener, errorListener, Priority.NORMAL);
            VolleySingleton volley = VolleySingleton.getVolleyInstance(getApplicationContext());
            volley.addRequest(httpService);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取
     */
    private void getAssay(String identify) {
        try {
            ArrayList<String> param = new ArrayList<>();
            ArrayList<String> value = new ArrayList<>();
            param.add("identify");
            value.add(identify);
            String methodName = "getAssay";

            Listener<String> listener = response -> {

                JSONObject object = JsonHelper.getJsonObject(response);
                try {
                    if (object != null) {
                        SharedPreferences preferences = getSharedPreferences("caption", MODE_PRIVATE);

                        String id = object.optString("id");
                        String assay = object.optString("assay");
                        String oldId = preferences.getString("assay", "");
                        if (!id.equals(oldId)) {
                            Editor editor = preferences.edit();
                            editor.putString("assay", id);
                            editor.apply();

                            Intent intent = new Intent(NotifyService.this, ContentInfo.class);
                            PendingIntent pi = PendingIntent.getActivity(NotifyService.this, 0,
                                    intent, PendingIntent.FLAG_UPDATE_CURRENT);
                            mNotification = new NotificationCompat.Builder(NotifyService.this, "default")
//											.setAutoCancel(true)
                                    .setTicker("化验有新信息!")
                                    .setSmallIcon(R.mipmap.ic_launcher)
                                    .setContentTitle("化验通知")
                                    .setContentText(assay)
                                    .setDefaults(
                                            Notification.DEFAULT_SOUND | Notification.DEFAULT_LIGHTS)
                                    .setWhen(System.currentTimeMillis())
                                    // 设改通知将要启动程序的Intent
                                    .setContentIntent(pi).build();
                            mNotification.flags = Notification.FLAG_AUTO_CANCEL;
                            // 发送通知
                            nmManager.notify(1, mNotification);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            };

            ErrorListener errorListener = error -> {
            };

            VolleyCallWebService httpService = new VolleyCallWebService(methodName, param, value, listener, errorListener, Priority.NORMAL);
            VolleySingleton volley = VolleySingleton.getVolleyInstance(getApplicationContext());
            volley.addRequest(httpService);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private String getUserName() {
        SharedPreferences preferences = getSharedPreferences("caption", MODE_PRIVATE);
        return preferences.getString("company", "");
    }
    private void getWeight() {
        try {

            ArrayList<String> param = new ArrayList<>();
            ArrayList<String> value = new ArrayList<>();
            String methodName = "getMaxWeightId";

            param.add("userName");
            value.add(getUserName());
            Listener<String> listener = response -> {

                JSONObject object = JsonHelper.getJsonObject(response);
                try {
                    if (object != null) {
                        SharedPreferences preferences = getSharedPreferences("caption", MODE_PRIVATE);

                        String id = object.optString("序号");
                        String jhdanid = object.optString("计划单号");
                        String money = object.optString("收支量");
                        String action = object.optString("动作");
                        if (!TextUtils.isEmpty(id)) {
                            String oldId = preferences.getString("id", "");
                            if (!id.equals(oldId)) {
                                Editor editor = preferences.edit();
                                editor.putString("id", id);
                                editor.apply();

                                Intent intent = new Intent(NotifyService.this, CollectWeigh.class);
                                intent.putExtra("planId", jhdanid);
                                PendingIntent pi = PendingIntent.getActivity(NotifyService.this, 0,
                                        intent, PendingIntent.FLAG_UPDATE_CURRENT);
                                mNotification = new NotificationCompat.Builder(NotifyService.this, "default")
//											.setAutoCancel(true)
                                        .setTicker("称重有新信息!")
                                        .setSmallIcon(R.mipmap.ic_launcher)
                                        .setContentTitle("财务通知")
                                        .setContentText("计划单号:" + jhdanid + ", " + action + ",金额: " + money)
                                        .setDefaults(
                                                Notification.DEFAULT_SOUND | Notification.DEFAULT_LIGHTS)
                                        .setWhen(System.currentTimeMillis())
                                        // 设改通知将要启动程序的Intent
                                        .setContentIntent(pi).build();
                                mNotification.flags = Notification.FLAG_AUTO_CANCEL;
                                // 发送通知
                                nmManager.notify(1, mNotification);
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            };

            ErrorListener errorListener = error -> {
            };

            VolleyCallWebService httpService = new VolleyCallWebService(methodName, param, value, listener, errorListener, Priority.NORMAL);
            VolleySingleton volley = VolleySingleton.getVolleyInstance(getApplicationContext());
            volley.addRequest(httpService);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}